import Fingerprint2 from 'fingerprintjs2'
import UAParser from 'ua-parser-js'

/**
 * 获取设备指纹信息
 * @var uaparser
 * ```json
 * {
 *   ua: "",
 *   browser: {
 *     name: "",
 *     version: ""
 *   },
 *   engine: {
 *     name: "",
 *     version: ""
 *   },
 *   os: {
 *     name: "",
 *     version: ""
 *   },
 *   device: {
 *     model: "",
 *     type: "",
 *     vendor: ""
 *   },
 *   cpu: {
 *     architecture: ""
 *   }
 * }
 * ```
 */
export const getFingerprintID = () => {
  return new Promise((resolve, reject) => {
    Fingerprint2.get((components) => {
      let userAgent
      const values = components.map((component) => {
        if (component.key === 'userAgent') {
          userAgent = component.value
        }
        return component.value
      })
      const murmur = Fingerprint2.x64hash128(values.join(''), 31)
      const uaparser = new UAParser(userAgent)
      const data = Object.assign({}, uaparser.getResult(), {
        sn: murmur
      })
      return resolve(data)
    })
  })
}

/**
 * 同步获取设备信息
 */
export const asyncDevice = async() => {
  const device = await getFingerprintID()
  return device
}

/**
 * 检测设备信息
 */
export const detecteDevice = (device) => {
  const name = device.toLowerCase()
  const uaparser = new UAParser()
  const deviceData = uaparser.getResult()
  // console.log(deviceData)
  if (name === 'weixin' || name === 'wechat') {
    if (/wechat/i.test(deviceData.browser.name) || /micromessenger/i.test(deviceData.ua)) {
      return true
    } else {
      return false
    }
  } else if (name === 'android' || name === 'adr' || name === 'ios') {
    if (deviceData.os.name.toLowerCase() === name) {
      return true
    } else {
      return false
    }
  } else if (name === 'mobile') {
    if (deviceData.device.type.toLowerCase() === name) {
      return true
    } else {
      return false
    }
  } else {
    const content = (deviceData.os.name + deviceData.device.type + deviceData.browser.name).toLowerCase()
    if (content.indexOf(name) > -1) {
      return true
    } else {
      return false
    }
  }
}
